package com.axxc.jpa.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.axxc.jpa.annotation.ParamNotBlankCheck;
import com.axxc.jpa.annotation.SaveOrUpdate;

/**
 * @ClassName: SaveOrUpdateInteceptor
 * @Description: 扫描自定义注解
 * @author xxc
 * @date 2018年9月17日 上午10:37:22
 * @see {@link https://gitee.com/biuabiu }
 * @see
 *      <p>
 *      定义的拦截器,需要注册到拦截器链中 注册拦截器 见
 *      {@linkplain com.axxc.jpa.config.SelfDefinitionInteceptorConfig }
 */

public class SaveOrUpdateInteceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("在请求处理之前进行调用（Controller方法调用之前）");
		if (handler instanceof HandlerMethod) {
			// 对应一个Webhandler即对应controller中的一个方法
			HandlerMethod hm = (HandlerMethod) handler;
			Method method = hm.getMethod();// 获取该方法
			boolean isHas = method.isAnnotationPresent(SaveOrUpdate.class);// 测试一个保存或修改的注解
			if (isHas) {
				SaveOrUpdate savaOrUpdate = method.getDeclaredAnnotation(SaveOrUpdate.class);
				System.out.println(savaOrUpdate.value());
				String[] params = savaOrUpdate.param();

				for (String param : params) {
					if (StringUtils.isNotBlank(param)) {
						String paramValue = request.getParameter(param.trim());
						System.out.println(paramValue);
					}
				}
			}
			ParamNotBlankCheck notBlankCheck = method.getDeclaredAnnotation(ParamNotBlankCheck.class);
			if (notBlankCheck != null) {
				String[] params = notBlankCheck.params();// 参数校验
				if (ArrayUtils.isNotEmpty(params)) {
					for (String param : params) {
						String paramValue = request.getParameter(param);
						if (StringUtils.isBlank(paramValue)) {
							throw new IllegalArgumentException(notBlankCheck.msg());
						}
					}
				}
			}
			return true;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
	}

}
